<template>
  <div class="tuijian-detail2">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/selection' }">干部选任</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/selection/tuijian' }">民主推荐</el-breadcrumb-item>
    </el-breadcrumb>
    <section class="wboxnoborder">
      <div :style="'height:'+tableHeight+'px'">
        <el-scrollbar style="height: calc(100% + 16px);">
          <el-form ref="form"
            :model="tuijianForm"
            label-width="120px"
            label-position="right"
            :inline="true" style="margin:15px;">
            <el-form-item label="动议岗位单位">
              {{tuijianForm.unitName}}
            </el-form-item>
            <el-form-item label="动议岗位职务">
              {{tuijianForm.jobName}}
            </el-form-item>
            <el-form-item label="动议岗位职级">
              {{tuijianForm.jobLevel}}
            </el-form-item>
            <div style="clear:both"></div>
            <el-form-item label="推荐单位">
              <el-autocomplete style="width:400px" v-model="tuijianForm.comp" :fetch-suggestions="querySearch" placeholder="请输入单位名称关键字" :trigger-on-focus="false" ></el-autocomplete>
            </el-form-item>
            <el-form-item label="推荐方式">
              <el-radio-group v-model="tuijianForm.radio">
                <el-radio :label="1">只谈话调研推荐</el-radio>
                <el-radio :label="2">先谈话调研推荐再会议推荐</el-radio>
                <el-radio :label="3">先会议推荐再谈话调研推荐</el-radio>
              </el-radio-group>
            </el-form-item>
            <div style="clear:both"></div>
            <el-form-item label="谈话推荐时间">
                <el-date-picker
                  v-model="tuijianForm.thdate"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                 >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="参加谈话推荐人数">
                <el-input-number v-model="tuijianForm.thnum" :min="1" label=""></el-input-number>
            </el-form-item>
            <div style="clear:both"></div>
            <el-form-item label="推荐" style="clear:both">
              <el-input v-model="tuijianForm.thipt" style="float:left;width:100px;"></el-input>
              <el-input-number v-model="tuijianForm.thnum2" :min="1" label="" style="margin-left:10px;"></el-input-number>
              人
              <el-button type="primary" @click="addAsyncItem">增加</el-button>
            </el-form-item>
            <div v-for="item in tuijianForm.asyncItem" :key="item.id" style="clear:both">
              <el-form-item label="推荐">
                  <el-input v-model="item.thipt" style="float:left;width:100px;"></el-input>
                  <el-input-number v-model="item.thnum" :min="1" label="" style="margin-left:10px;"></el-input-number>
                  人
                  <el-button type="danger" @click.prevent="delAsyncItem(item)">删除</el-button>
              </el-form-item>
            </div>
            <div v-show="tuijianForm.radio!==1">
              <el-form-item label="会议推荐时间">
                <el-date-picker
                  v-model="tuijianForm.hydate"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="参加会议推荐人数">
                <el-input-number v-model="tuijianForm.hynum" :min="1" label=""></el-input-number>
              </el-form-item>
              <div style="clear:both"></div>
              <el-form-item label="推荐">
                <el-input v-model="tuijianForm.hyipt" style="float:left;width:100px;"></el-input>
                <el-input-number v-model="tuijianForm.hynum2" :min="1" label="" style="margin-left:10px;"></el-input-number>
                人
                <el-button type="primary" @click="addAsyncItem2">增加</el-button>
              </el-form-item>
              <div v-for="item in tuijianForm.asyncItem2" :key="item.id" style="clear:both">
                <el-form-item label="推荐">
                  <el-input v-model="item.hyipt" style="float:left;width:100px;"></el-input>
                  <el-input-number v-model="item.hynum" :min="1" label="" style="margin-left:10px;"></el-input-number>
                  人
                  <el-button type="danger" @click.prevent="delAsyncItem2(item)">删除</el-button>
                </el-form-item>
              </div>
            </div>
            <el-form-item label="上传附件" prop="file">
                <el-upload
                  class="upload-demo"
                  :action="this.$http.defaults.baseURL+this.$http.defaults.selectionAPI +'api/gen/file/upload/'"
                  :on-success="handleUploadSucc"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-error='uploadError'
                  :multiple="true"
                  :file-list="fileList">
                  <el-button type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>
            <div style="clear:both"></div>
            <el-form-item label="备注">
                <el-input v-model="tuijianForm.beizhu" style="width:800px"></el-input>
            </el-form-item>
            <div style="clear:both"></div>
            <el-form-item label="工作组人员">
                <el-input v-model="tuijianForm.workgroup" style="width:800px"></el-input>
            </el-form-item>
            <div style="clear:both"></div>
            <el-form-item>
              <el-button type="primary" @click="onSubmit(1)" style="margin-left:120px;" :loading="loading">确认保存</el-button>
              <el-button type="success" @click="onSubmit(2)" :loading="loading">确定为考察对象，进入考察环节</el-button>
              <el-button type="danger" @click="onSubmit(3)" :loading="loading">未确定考察对象，干部选任终止</el-button>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
    </section>
  </div>
</template>

<script>
export default {
  name: 'tuijian-detail2',
  data () {
    return {
      loading: false,
      tableHeight: 100,
      params: {
        busCandidatePersonId: '',
        unitName: '',
        jobName: '',
        jobLevel: '',
        personId: ''
      },
      tuijianForm: {
        comp: '',
        radio: '',
        thdate: '',
        thnum: '',
        thipt: '',
        thnum2: '',
        asyncItem: [
          {
            thnum: '',
            thipt: '',
            id: '001'
          }
        ],
        hydate: '',
        hynum: '',
        hyipt: '',
        hynum2: '',
        asyncItem2: [
          {
            hynum: '',
            hyipt: '',
            id: '00011'
          }
        ],
        beizhu: '',
        workgroup: ''
      },
      files: [],
      fileList: []
    }
  },
  methods: {
    querySearch (queryString, cb) {
      return this.getunits(this, queryString, cb)
    },
    getunits (self, queryString, cb) {
      let para = {
        unitname: queryString
      }
      self.$http
        .post(`/api/prj/searchunit/`, para)
        .then(function (response) {
          console.log('获取成功')
          var results = response.data
          let newArr = []
          results.forEach(function (item) {
            let obj = {'value': item}
            newArr.push(obj)
          })
          cb(newArr)
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    handleUploadSucc (response, file, fileList) {
      console.log(response)
      if (response.success) {
        this.files.push(response.result[0])
        this.$message({
          message: '上传成功！' + response.message,
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
      }
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    uploadError (err) {
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    addAsyncItem () {
      this.tuijianForm.asyncItem.push({
        thipt: '',
        thnum: '',
        id: Date.now()
      })
    },
    delAsyncItem (item) {
      var index = this.tuijianForm.asyncItem.indexOf(item)
      if (index !== -1) {
        this.tuijianForm.asyncItem.splice(index, 1)
      }
    },
    addAsyncItem2 () {
      this.tuijianForm.asyncItem2.push({
        hyipt: '',
        hynum: '',
        id: Date.now()
      })
    },
    delAsyncItem2 (item) {
      var index = this.tuijianForm.asyncItem2.indexOf(item)
      if (index !== -1) {
        this.tuijianForm.asyncItem2.splice(index, 1)
      }
    },
    onSubmit (req) {
      this.loading = true
      console.log('submit data', this.tuijianForm)
      if (this.tuijianForm.comp === '') {
        this.$message({
          message: '推荐单位不能为空',
          type: 'warning'
        })
        return
      }
      if (this.tuijianForm.radio === '') {
        this.$message({
          message: '请选择推荐方式',
          type: 'warning'
        })
        return
      }
      if (this.tuijianForm.thipt === '' && this.tuijianForm.hyipt === '') {
        this.$message({
          message: '谈话推荐或会议推荐至少填一人',
          type: 'warning'
        })
        return
      }
      if (this.tuijianForm.workgroup === '') {
        this.$message({
          message: '工作组人员不能为空',
          type: 'warning'
        })
        return
      }
      console.log('hi')
      // 获取会议推荐，谈话推荐提交格式
      let thpss = [...this.tuijianForm.asyncItem]
      if (this.tuijianForm.thipt !== '') {
        thpss.push({
          thipt: this.tuijianForm.thipt,
          thnum: this.tuijianForm.thnum2
        })
      }
      let arr = []
      for (let i of thpss) {
        if (i.thipt !== '') {
          arr.push({
            name: i.thipt,
            times: i.thnum
          })
        }
      }
      let arrstr = JSON.stringify(arr)
      console.log('谈话推荐:', arr)
      let hypss = [...this.tuijianForm.asyncItem2]
      if (this.tuijianForm.hyipt !== '') {
        hypss.push({
          hyipt: this.tuijianForm.hyipt,
          hynum: this.tuijianForm.hynum2
        })
      }
      let brr = []
      for (let i of hypss) {
        if (i.hyipt !== '') {
          brr.push({
            name: i.hyipt,
            times: i.hynum
          })
        }
      }
      let brrstr = JSON.stringify(brr)
      console.log('会议推荐：', brr)
      // 获取上传文件列表
      let crr = []
      for (let i of this.files) {
        crr.push(i.id)
      }
      console.log('文件上传列表id:', crr)
      let url = this.$http.defaults.selectionAPI + 'api/selection/democraticRecommend/saveInfo'
      this.$http.post(url, {
        busCandidatePersonId: this.params.personId,
        recommendUnit: this.tuijianForm.comp,
        recommendType: this.tuijianForm.radio,
        recommendTalkTimeStart: this.tuijianForm.thdate[0] || '',
        recommendTalkTimeEnd: this.tuijianForm.thdate[1] || '',
        recommendTalkTimes: this.tuijianForm.thnum,
        recommendTalkPersons: arrstr,
        recommendMeetingTimeStart: this.tuijianForm.hydate[0] || '',
        recommendMeetingTimeEnd: this.tuijianForm.hydate[1] || '',
        recommendMeetingTimes: this.tuijianForm.hynum,
        recommendMeetingPersons: brrstr,
        workingteam: this.tuijianForm.workgroup,
        remarks: this.tuijianForm.beizhu,
        stateRecommend: req,
        files: crr
      }).then(res => {
        console.log('submit succ res :', res)
        if (res.data.success) {
          this.loading = false
          if (req === 1) {
            this.$router.push({
              name: 'tuijian',
              params: {
                step: 2
              }
            })
          } else if (req === 2) {
            this.$router.push({
              name: 'tuijian',
              params: {
                step: 3
              }
            })
          } else if (req === 3) {
            this.$router.push({
              name: 'tuijian',
              params: {
                step: 3
              }
            })
          }
        } else {
          this.loading = false
          this.$message({
            message: '保存失败:' + res.data.message,
            type: 'error'
          })
        }
      })
    },
    formatFiles (files) {
      if (files && files.length > 0) {
        let newfiles = []
        for (let i = 0; i < files.length; i++) {
          newfiles.push({name: files[i].fileName + '.' + files[i].fileType, id: files[i].id})
        }
        console.log(newfiles)
        return newfiles
      }
    },
    getData (id) {
      let url = this.$http.defaults.selectionAPI + 'api/selection/democraticRecommend/getInfo'
      console.log('id:' + id)
      this.$http.get(url, {
        params: {
          personId: id
        }
      }).then(res => {
        console.log(res)
        if (res.data.success === true) {
          let rs = res.data.result
          let arr = {}
          arr.unitName = this.params.unitName
          arr.jobName = this.params.jobName
          arr.jobLevel = this.params.jobLevel
          arr.comp = rs.recommendUnit
          arr.radio = rs.recommendType
          if (rs.recommendTalkTimeStart && rs.recommendTalkTimeEnd) {
            arr.thdate = [rs.recommendTalkTimeStart, rs.recommendTalkTimeEnd]
          } else {
            arr.thdate = ''
          }
          arr.thnum = rs.recommendTalkTimes
          let sarr = [...JSON.parse(rs.recommendTalkPersons)]
          if (sarr.length > 0) {
            arr.thipt = sarr[0].name
            arr.thnum2 = sarr[0].times
            let sarr2 = []
            for (let i of sarr.slice(1)) {
              sarr2.push({
                thipt: i.name,
                thnum: i.times,
                id: Date.now()
              })
            }
            arr.asyncItem = sarr2
          } else {
            arr.thipt = ''
            arr.thnum2 = ''
            arr.asyncItem = []
          }
          if (rs.recommendMeetingTimeStart && rs.recommendMeetingTimeEnd) {
            arr.hydate = [rs.recommendMeetingTimeStart, rs.recommendMeetingTimeEnd]
          } else {
            arr.hydate = ''
          }
          arr.hynum = rs.recommendMeetingTimes
          let sbrr = JSON.parse(rs.recommendMeetingPersons)
          if (sbrr.length > 0) {
            console.log('回显sbrr:', sbrr)
            arr.hyipt = sbrr[0].name
            arr.hynum2 = sbrr[0].times
            let sbrr2 = []
            for (let i of sbrr.slice(1)) {
              sbrr2.push({
                hynum: i.times,
                hyipt: i.name,
                id: Date.now()
              })
            }
            arr.asyncItem2 = sbrr2
          } else {
            arr.hyipt = ''
            arr.hynum2 = ''
            arr.asyncItem2 = []
          }
          arr.beizhu = rs.remarks
          arr.workgroup = rs.workingteam
          console.log('回显数据arr:', arr)
          this.tuijianForm = arr
          this.fileList = this.formatFiles(rs.files)
        }
      })
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - 165
      })
    }
  },
  mounted () {
    let params = this.$route.params
    console.log('this.params:', params)
    // console.log(params.busCandidatePersonId)
    this.params.unitName = params.unitName
    this.params.jobName = params.jobName
    this.params.jobLevel = params.jobLevel
    this.params.personId = params.busCandidatePersonId
    this.getData(params.busCandidatePersonId)

    this.tableresize(this)
    let _this = this
    window.onresize = function windowResize () {
      // 通过捕获系统的onresize事件触发我们需要执行的事件
      _this.tableresize(_this)
    }
  }
}
</script>
<style>
.tuijian-detail2 .wboxnoborder .el-table{
  border: #95B8E7 solid 1px;
}
.tuijian-detail2 .wboxnoborder .el-table th{
  font-weight: normal;
  background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  text-align: center;
  border-right: #95B8E7 solid 1px;
  border-bottom: #95B8E7 solid 1px;
  min-height: 30px;
  line-height:30px;
}
.tuijian-detail2 .wboxnoborder .el-table td, .el-table th{
  padding:0;
  font-size:var(--size14) !important;
  line-height: 20px;
  font-family: '宋体';
  text-align: center;
}
.tuijian-detail2 .el-table__row{
  height: 50px;
}
</style>
<style scoped>
.tuijian-detail2 {
  width: 100%;
}
.sel-tit {
  width: 100%;
  height: 32px;
  line-height: 32px;
  padding: 0 15px;
  box-sizing: border-box;
  float: left;
  color: #303133;
  text-align: right;
  font-size: 16px;
}
.sel-con {
  width: 100%;
  height: 32px;
  line-height: 32px;
  padding: 0 15px;
  box-sizing: border-box;
  float: left;
  color: #909399;
  border-bottom: 0.5px solid #909399;
  font-size: 14px;
}
.tuijian-detail2 .wboxnoborder {
  padding: 0;
  width: 100%;
  background-color: #fff;
  margin: 0 10px;
  overflow: hidden;
}
</style>
